package com.wnxy.sk.product.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    // 交换机
    @Bean("orderExchange")
    public Exchange orderExchange() {
        return new TopicExchange("order-exchange", true, false);
    }
    // 队列
    @Bean("ttlOrderQueue")
    public Queue ttlOrderQueue() {
        Map params = new HashMap();
        params.put("x-message-ttl", 30000);
        params.put("x-dead-letter-exchange", "order-dead-letter-exchange");
        params.put("x-dead-letter-routing-key", "dead.letter.order");
        return new Queue("ttl-order-queue", true, false, false, params);
    }
    // 绑定
    @Bean
    public Binding bindTTLOrderQueue(
            @Qualifier("ttlOrderQueue") Queue queue,
            @Qualifier("orderExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange)
                .with("order.#").noargs();
    }

    // 死信交换机
    @Bean("orderDeadLetterExchange")
    public Exchange orderDeadLetterExchange() {
        return new TopicExchange("order-dead-letter-exchange", true, false);
    }
    // 死信队列
    @Bean("orderDeadLetterQueue")
    public Queue orderDeadLetterQueue() {
        return new Queue("order-dead-letter-queue", true, false, false);
    }
    // 死信绑定
    @Bean
    public Binding bindOrderDeadLetterQueue(
            @Qualifier("orderDeadLetterQueue") Queue queue,
            @Qualifier("orderDeadLetterExchange") Exchange exchange) {
        return BindingBuilder.bind(queue)
                .to(exchange)
                .with("dead.letter.order").noargs();
    }

    @Bean
    public RabbitAdmin rabbitAdmin(
            ConnectionFactory factory,
            Exchange orderExchange,
            Exchange orderDeadLetterExchange,
            Queue ttlOrderQueue,
            Queue orderDeadLetterQueue) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(factory);
        rabbitAdmin.setAutoStartup(true);
        rabbitAdmin.declareExchange(orderExchange);
        rabbitAdmin.declareExchange(orderDeadLetterExchange);
        rabbitAdmin.declareQueue(ttlOrderQueue);
        rabbitAdmin.declareQueue(orderDeadLetterQueue);
        return rabbitAdmin;
    }

}